import React, { useState, useEffect } from "react";
import { Button, Image, Popconfirm, Space, Tag } from "antd";
import MyTemplate1 from "../../shared/myTemplate1";
import useCloseLoadingOnMount from "../../../utils/hook/useCloseLoadingOnMount";
import { useNavigate } from "react-router-dom";
import suppliersApi from "../../../apis/suppliersApi";
import { getImagePath, promptResult2 } from "../../../utils/common";

const SupplierManage = () => {
  useCloseLoadingOnMount();
  const [dataSource, setDataSource] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    key: "",
    total: 0,
  });
  const [flag, setFlag] = useState(false);
  const navigate = useNavigate();

  // 模拟API请求
  const fetchSuppliers = async () => {
    setLoading(true);
    const res = await suppliersApi.getSuppliersPagination({
      page: pagination.current,
      limit: pagination.pageSize,
      key: pagination.key,
    });
    if (res.status >= 0) {
      setDataSource(res.data.data);
      setPagination({
        ...pagination,
        total: res.data.total,
      });
    }
    setLoading(false);
  };

  // 监听分页对象属性变化，当变化时进行分页
  useEffect(() => {
    fetchSuppliers();
  }, [pagination.current]);

  useEffect(() => {
    if (flag) {
      if (pagination.current != 1) {
        setPagination({ ...pagination, current: 1 });
      } else {
        fetchSuppliers();
      }
    }
    setFlag(true);
  }, [pagination.pageSize, pagination.key]);

  const columns = [
    {
      title: "店铺名称",
      dataIndex: "shopName",
      key: "shopName",
    },
    {
      title: "账号",
      dataIndex: "account",
      key: "account",
    },
    {
      title: "经营类别",
      dataIndex: "typeName",
      key: "typeName",
    },
    {
      title: "企业名称",
      dataIndex: "enterpriseName",
      key: "enterpriseName",
    },
    {
      title: "logo",
      dataIndex: "logo",
      key: "logo",
      render: (text, row) => {
        if (text.length > 0) {
          return (
            <Image src={getImagePath(row.id, text)} height={"60px"}></Image>
          );
        } else {
          return "-";
        }
      },
    },
    {
      title: "照片",
      dataIndex: "photo",
      key: "photo",
      render: (text, row) => {
        var images = text.split(",");
        if (images.length > 0) {
          return (
            <Image
              src={getImagePath(row.id, images[0])}
              height={"60px"}
            ></Image>
          );
        } else {
          return "-";
        }
      },
    },
    {
      title: "资质文件",
      dataIndex: "qualification",
      key: "qualification",
      render: (text, row) => {
        var images = text.split(",");
        if (images.length > 0) {
          return (
            <Image
              src={getImagePath(row.id, images[0])}
              height={"60px"}
            ></Image>
          );
        } else {
          return "-";
        }
      },
    },
    {
      title: "是否激活",
      dataIndex: "isActive",
      key: "isActive",
    },
    {
      title: "是否封禁",
      dataIndex: "isBan",
      key: "isBan",
    },
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "角色",
      dataIndex: "endpoint",
      key: "endpoint",
    },
    {
      title: "地址",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "公告",
      dataIndex: "announcement",
      key: "announcement",
    },
    {
      title: "头像",
      dataIndex: "avatar",
      key: "avatar",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "微信 ID",
      dataIndex: "openId",
      key: "openId",
    },
    {
      title: "电话",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "创建时间",
      dataIndex: "createTimeStr",
      key: "createTimeStr",
    },
    {
      title: "更新时间",
      dataIndex: "updateTimeStr",
      key: "updateTimeStr",
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      render: (_, record) => (
        <Space size="middle">
          <Button
            color="geekblue"
            variant="filled"
            onClick={() => handleDetail(record.id)}
          >
            详情
          </Button>
          <Popconfirm
            title="删除供应商"
            description={`你确定要删除"${record.account}"吗?`}
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button color="red" variant="filled">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleDelete = async (id) => {
    await promptResult2(
      suppliersApi.deleteSuppliers(id),
      () => {},
      fetchSuppliers
    );
  };

  const handleDetail = (id) => {
    navigate("detail/" + id);
  };

  const handleSearch = (e) => {
    setPagination({
      ...pagination,
      key: e.target.value,
    });
  };

  const handleAdd = () => {
    navigate("add");
  };

  return (
    <MyTemplate1
      searchProps={{
        placeholder: "搜索企业名称或账号",
        onChange: handleSearch,
      }}
      addButtonProps={{
        text: "新增供应商",
        onClick: handleAdd,
      }}
      columns={columns}
      dataSource={dataSource}
      loading={loading}
      pagination={pagination}
      onPageChange={(page, pageSize) => {
        setPagination({
          ...pagination,
          current: page,
          pageSize,
        });
      }}
    />
  );
};

export default SupplierManage;
